/**
 * Mutations业务层数据提交
 */
import storage from '@/utils/storage';

export default {
  saveUserInfo(state, userInfo) {
    state.userInfo = userInfo;
    storage.setItem('userInfo', userInfo);
  },
  saveCategory(state, category) {
    state.category = category;
    storage.setItem('category', category);
  },
  setList(state, payload) {
    state.category.list = payload;
    storage.setItem('category', state.category);
  },
  setCartList(state, payload) {
    state.list = payload;
    storage.setItem('list', state.list);
  },
  // 添加购物车
  insertCart(state, payload) {
    const sameIndex = state.list.findIndex(
      (goods) => goods.skuId === payload.skuId
    );
    if (sameIndex > -1) {
      const count = state.list[sameIndex].count;
      payload.count += count;
      state.list.splice(sameIndex, 1);
    }
    state.list.unshift(payload);
    storage.setItem('list', state.list);
  },
  // 修改购物车
  updateCart(state, goods) {
    // goods中字段有可能不完整，goods有的信息才去修改。
    // 1. goods中必需又skuId，才能找到对应的商品信息
    const updateGoods = state.list.find(item => item.skuId === goods.skuId)
    for (const key in goods) {
      if (goods[key] !== null && goods[key] !== undefined && goods[key] !== '') {
        updateGoods[key] = goods[key]
      }
    }
    storage.setItem('list', state.list);
  },
  // 删除购物车商品
  deleteCart(state, skuId) {
    const index = state.list.findIndex(item => item.skuId === skuId)
    state.list.splice(index, 1)
    storage.setItem('list', state.list);
  },
  // 全选商品
  selectedCartAll(state, payload) {
    for (let i in state.list) {
      if (payload.cartList[i] && payload.cartList[i].skuId === state.list[i].skuId) {
        state.list[i].selected = payload.isAll
      }
    }
    storage.setItem('list', state.list);
  },


};
